<!DOCTYPE HTML>
<html>
<head>
  <style>
    .title {
      text-align: center;
      position: relative;
    }
    .lang-switch, .settings-btn {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      background-color: #1E90FF;
      color: white;
      border: none;
      border-radius: 8px;
      padding: 8px 15px;
      font-size: 14px;
      cursor: pointer;
      box-shadow: 0 4px #999;
      transition: all 0.3s;
    }
    .lang-switch {
      right: 20px;
    }
    .settings-btn {
      left: 20px;
    }
    .lang-switch:hover, .settings-btn:hover {
      background-color: #0b7dda;
    }
    .lang-switch:active, .settings-btn:active {
      box-shadow: 0 2px #666;
      transform: translateY(-48%);
    }
    .button { 
      display: inline-block;
      width: 130px; /* 所有按钮的统一宽度 */
      height: 50px; /* 所有按钮的统一高度 */
      line-height: 50px; /* 使文本垂直居中 */
      font-size: 20px;
      cursor: pointer;
      text-align: center;
      text-decoration: none;
      outline: none;
      color: #fff;
      background-color: #1E90FF;
      border: none;
      border-radius: 10px;
      box-shadow: 0 9px #999;
    }
    .button:hover {background-color: #0b7dda}
    .button:active {
      background-color: #0b7dda;
      box-shadow: 0 5px #666;
      transform: translateY(4px);
    }

    /* 移动按钮的颜色设置 */
    .button-move {
      background-color: #FF1493; /* 洋红色 */
    }
    .button-move:hover {background-color: #FF69B4}
    .button-move:active {
      background-color: #FF69B4;
      box-shadow: 0 5px #666;
      transform: translateY(4px);
    }

    /* 姿态按钮的颜色设置 */
    .button-posture {
      background-color: #FFA500; /* 科技氛围的橙色 */
    }
    .button-posture:hover {background-color: #FFB347}
    .button-posture:active {
      background-color: #FFB347;
      box-shadow: 0 5px #666;
      transform: translateY(4px);
    }

    /* 待机模式的颜色设置 */
    .button-standby {
      background-color: #3A3A3A; /* 大疆无人机灰 */
    }
    .button-standby:hover {background-color: #4A4A4A}
    .button-standby:active {
      background-color: #4A4A4A;
      box-shadow: 0 5px #666;
      transform: translateY(4px);
    }

    .grid-container {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      justify-items: center;
      align-items: center;
      margin-top: 20px;
    }
    .grid-item-1 { grid-column: span 1; }
    .grid-item-2 { grid-column: span 2; }
    .grid-item-3 { grid-column: span 3; }
    .empty { visibility: hidden; }
    .empty-row { grid-column: span 3; height: 20px; }

    /* 速度控制区域样式 */
    .speed-control {
      max-width: 500px;
      margin: 10px auto;
      padding: 10px;
      background-color: #f5f5f5;
      border-radius: 15px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    .speed-label {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-bottom: 10px;
      text-align: center;
    }
    /* 速度档位按钮样式 */
    .speed-levels {
      display: flex;
      justify-content: center;
      gap: 10px;
      margin: 15px 0;
      flex-wrap: wrap;
    }
    .speed-btn {
      padding: 10px 20px;
      border: 2px solid #1E90FF;
      background-color: white;
      color: #1E90FF;
      border-radius: 25px;
      cursor: pointer;
      font-size: 16px;
      font-weight: bold;
      transition: all 0.3s ease;
      min-width: 80px;
    }
    .speed-btn:hover {
      background-color: #1E90FF;
      color: white;
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(30, 144, 255, 0.3);
    }
    .speed-btn.active {
      background-color: #1E90FF;
      color: white;
      box-shadow: 0 2px 4px rgba(30, 144, 255, 0.3);
    }
    .speed-btn.active:hover {
      background-color: #0b7dda;
    }

    /* 页脚署名样式 */
    .footer {
      margin-top: 40px;
      padding: 20px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      text-align: center;
      border-radius: 10px 10px 0 0;
      box-shadow: 0 -4px 6px rgba(0, 0, 0, 0.1);
    }
    .footer-content {
      max-width: 800px;
      margin: 0 auto;
    }
    .footer-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }
    .footer-links {
      display: flex;
      justify-content: center;
      gap: 15px;
      flex-wrap: nowrap;
      margin-top: 12px;
    }
    .footer-link {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      color: white;
      text-decoration: none;
      font-size: 14px;
      padding: 8px 15px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 20px;
      transition: all 0.3s;
    }
    .footer-link:hover {
      background: rgba(255, 255, 255, 0.3);
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }
    .footer-icon {
      width: 20px;
      height: 20px;
    }

    /* 模态框样式 */
    .modal {
      display: none;
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
    }
    .modal-content {
      background-color: #fefefe;
      margin: 5% auto;
      padding: 20px;
      border: 1px solid #888;
      border-radius: 15px;
      width: 90%;
      max-width: 500px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.3);
    }
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 2px solid #1E90FF;
    }
    .modal-title {
      font-size: 20px;
      font-weight: bold;
      color: #333;
    }
    .close {
      color: #aaa;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
      line-height: 20px;
    }
    .close:hover {
      color: #000;
    }
    .form-group {
      margin-bottom: 15px;
    }
    .form-label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
      color: #333;
    }
    .form-input {
      width: 100%;
      padding: 10px;
      border: 2px solid #ddd;
      border-radius: 5px;
      font-size: 14px;
      box-sizing: border-box;
    }
    .form-input:focus {
      outline: none;
      border-color: #1E90FF;
    }
    .form-actions {
      display: flex;
      gap: 10px;
      margin-top: 20px;
    }
    .btn-primary {
      flex: 1;
      padding: 10px;
      background-color: #1E90FF;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
      font-weight: bold;
    }
    .btn-primary:hover {
      background-color: #0b7dda;
    }
    .btn-secondary {
      flex: 1;
      padding: 10px;
      background-color: #666;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
    }
    .btn-secondary:hover {
      background-color: #555;
    }
    .btn-danger {
      padding: 10px;
      background-color: #dc3545;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      margin-top: 10px;
      width: 100%;
    }
    .btn-danger:hover {
      background-color: #c82333;
    }
    .info-box {
      background-color: #e7f3ff;
      border-left: 4px solid #1E90FF;
      padding: 10px;
      margin: 10px 0;
      border-radius: 5px;
      font-size: 14px;
    }
    .wifi-qr {
      text-align: center;
      margin: 15px 0;
      padding: 10px;
      background-color: #f5f5f5;
      border-radius: 5px;
    }
    .wifi-qr-text {
      font-family: monospace;
      font-size: 12px;
      word-break: break-all;
      margin-top: 10px;
    }
    .status-message {
      margin-top: 10px;
      padding: 10px;
      border-radius: 5px;
      font-size: 14px;
      display: none;
    }
    .status-success {
      background-color: #d4edda;
      color: #155724;
      border: 1px solid #c3e6cb;
    }
    .status-error {
      background-color: #f8d7da;
      color: #721c24;
      border: 1px solid #f5c6cb;
    }
  </style>
</head>
<body>
  <h1 class="title">
    <span id="pageTitle">机器人控制</span>
    <button class="settings-btn" onclick="openSettings()" data-zh="⚙️ 设置" data-en="⚙️ Settings">⚙️ 设置</button>
    <button class="lang-switch" onclick="toggleLanguage()">English</button>
  </h1>

  <center><span align="center" style="text-align: center; display: inline-block;padding: 5px; font-size: 120%;font-weight: bold;"><a style="width:200px; height:50px;" href="/calibration">
    <button id="CALIBRATEPAGE" type="button" onclick="buttonclick(this);" style="width:200px; height: 30px; Text-align: center;">Calibration: Start | Save</button></a></span></center><br>

  <!-- 速度控制区域 -->
  <div class="speed-control">
    <div class="speed-label">运动速度控制</div>
    <div class="speed-levels">
      <button class="speed-btn" data-speed="0.25" data-zh="极慢" data-en="Slowest">极慢</button>
      <button class="speed-btn" data-speed="0.33" data-zh="慢速" data-en="Slow">慢速</button>
      <button class="speed-btn active" data-speed="0.5" data-zh="中速" data-en="Medium">中速</button>
      <button class="speed-btn" data-speed="1.0" data-zh="快速" data-en="Fastest">快速</button>
    </div>
  </div>
  
  <div class="grid-container">
    <button class="button button-posture grid-item-1" onclick="sendCommand(9)" data-zh="旋转X" data-en="RotateX">旋转X</button>
    <button class="button button-posture grid-item-1" onclick="sendCommand(10)" data-zh="旋转Y" data-en="RotateY">旋转Y</button>
    <button class="button button-posture grid-item-1" onclick="sendCommand(11)" data-zh="旋转Z" data-en="RotateZ">旋转Z</button>
    <button class="button button-posture grid-item-3" onclick="sendCommand(12)" data-zh="扭腰" data-en="Twist">扭腰</button>
    
    <div class="empty-row"></div>
    
    <button class="button grid-item-1" onclick="sendCommand(4)" data-zh="左转" data-en="TurnLeft">左转</button>
    <div class="empty grid-item-1"></div>
    <button class="button grid-item-1" onclick="sendCommand(5)" data-zh="右转" data-en="TurnRight">右转</button>
    
    <button class="button grid-item-1" onclick="sendCommand(2)" data-zh="快跑" data-en="Run">快跑</button>
    <button class="button button-move grid-item-1" onclick="sendCommand(1)" data-zh="前进" data-en="Forward">前进</button>
    <button class="button grid-item-1" onclick="sendCommand(8)" data-zh="爬行" data-en="Climb">爬行</button>
    
    <button class="button button-move grid-item-1" onclick="sendCommand(6)" data-zh="左移" data-en="ShiftLeft">左移</button>
    <button class="button button-standby grid-item-1" onclick="sendCommand(0)" data-zh="待机" data-en="Standby">待机</button>
    <button class="button button-move grid-item-1" onclick="sendCommand(7)" data-zh="右移" data-en="ShiftRight">右移</button>
    <button class="button button-move grid-item-3" onclick="sendCommand(3)" data-zh="后退" data-en="Backward">后退</button>
  </div>

  <!-- AP配置模态框 -->
  <div id="settingsModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <span class="modal-title" id="modalTitle">WiFi AP 配置</span>
        <span class="close" onclick="closeSettings()">&times;</span>
      </div>
      <div id="settingsForm">
        <div class="form-group">
          <label class="form-label" id="labelSSID">AP 名称 (SSID)</label>
          <input type="text" id="apSSID" class="form-input" placeholder="NodeHexa-XXXX" maxlength="31">
        </div>
        <div class="form-group">
          <label class="form-label" id="labelPassword">密码 (8-63字符，留空为开放网络)</label>
          <input type="password" id="apPassword" class="form-input" placeholder="留空为开放网络" maxlength="63">
        </div>
        <div class="info-box" id="currentInfo">
          <strong>当前配置：</strong><br>
          <span id="currentSSID">加载中...</span>
        </div>
        <div class="form-actions">
          <button class="btn-primary" onclick="saveAPConfig()" id="btnSave">保存</button>
          <button class="btn-secondary" onclick="closeSettings()" id="btnCancel">取消</button>
        </div>
        <button class="btn-danger" onclick="resetAPConfig()" id="btnReset">恢复默认配置</button>
        <div class="status-message" id="statusMessage"></div>
      </div>
      <div id="pendingInfo" style="display: none;">
        <div class="info-box">
          <strong>配置已更新！</strong><br>
          <p id="pendingMessage">设备将在3秒后重启，请连接到新的AP：</p>
          <div class="wifi-qr">
            <div><strong id="newSSID">-</strong></div>
            <div id="newPassword" style="margin-top: 5px;"></div>
            <div class="wifi-qr-text" id="wifiQRText"></div>
          </div>
          <p style="font-size: 12px; color: #666; margin-top: 10px;">
            连接后访问 http://192.168.4.1 完成确认
          </p>
        </div>
      </div>
    </div>
  </div>

  <!-- 页脚署名 -->
  <footer class="footer">
    <div class="footer-content">
      <div class="footer-title" id="footerTitle">开源项目 · NodeHexa 六足机器人</div>
      <div class="footer-links">
        <a href="https://space.bilibili.com/85652131" target="_blank" class="footer-link" title="B站主页">
          <svg class="footer-icon" viewBox="0 0 24 24" fill="currentColor">
            <path d="M17.813 4.653h.854c1.51.054 2.769.578 3.773 1.574 1.004.995 1.524 2.249 1.56 3.76v7.36c-.036 1.51-.556 2.769-1.56 3.773s-2.262 1.524-3.773 1.56H5.333c-1.51-.036-2.769-.556-3.773-1.56S.036 18.858 0 17.347v-7.36c.036-1.511.556-2.765 1.56-3.76 1.004-.996 2.262-1.52 3.773-1.574h.774l-1.174-1.12a1.234 1.234 0 0 1-.373-.906c0-.356.124-.658.373-.907l.027-.027c.267-.249.573-.373.92-.373.347 0 .653.124.92.373L9.653 4.44c.071.071.134.142.187.213h4.267a.836.836 0 0 1 .16-.213l2.853-2.747c.267-.249.573-.373.92-.373.347 0 .662.151.929.4.267.249.391.551.391.907 0 .355-.124.657-.373.906zM5.333 7.24c-.746.018-1.373.276-1.88.773-.506.498-.769 1.13-.786 1.894v7.52c.017.764.28 1.395.786 1.893.507.498 1.134.756 1.88.773h13.334c.746-.017 1.373-.275 1.88-.773.506-.498.769-1.129.786-1.893v-7.52c-.017-.765-.28-1.396-.786-1.894-.507-.497-1.134-.755-1.88-.773zM8 11.107c.373 0 .684.124.933.373.25.249.383.569.4.96v1.173c-.017.391-.15.711-.4.96-.249.25-.56.374-.933.374s-.684-.125-.933-.374c-.25-.249-.383-.569-.4-.96V12.44c0-.373.129-.689.386-.947.258-.257.574-.386.947-.386zm8 0c.373 0 .684.124.933.373.25.249.383.569.4.96v1.173c-.017.391-.15.711-.4.96-.249.25-.56.374-.933.374s-.684-.125-.933-.374c-.25-.249-.383-.569-.4-.96V12.44c.017-.391.15-.711.4-.96.249-.249.56-.373.933-.373Z"/>
          </svg>
          <span id="bilibiliText">B站: 智造师_RoboticsCV</span>
        </a>
        <a href="https://github.com/ViolinLee" target="_blank" class="footer-link" title="GitHub主页">
          <svg class="footer-icon" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z"/>
          </svg>
          <span id="githubText">GitHub: ViolinLee</span>
        </a>
        <span class="footer-link" title="微信公众号" style="cursor: default;">
          <svg class="footer-icon" viewBox="0 0 24 24" fill="currentColor">
            <path d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.326.326 0 0 0 .167-.054l1.903-1.114a.864.864 0 0 1 .717-.098 10.16 10.16 0 0 0 2.837.403c.276 0 .543-.027.811-.05-.857-2.578.157-4.972 1.932-6.446 1.703-1.415 3.882-1.98 5.853-1.838-.576-3.583-4.196-6.348-8.596-6.348zM5.785 5.991c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178A1.17 1.17 0 0 1 4.623 7.17c0-.651.52-1.18 1.162-1.18zm5.813 0c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178 1.17 1.17 0 0 1-1.162-1.178c0-.651.52-1.18 1.162-1.18zm5.34 2.867c-1.797-.052-3.746.512-5.28 1.786-1.72 1.428-2.687 3.72-1.78 6.22.942 2.453 3.666 4.229 6.884 4.229.826 0 1.622-.12 2.361-.336a.722.722 0 0 1 .598.082l1.584.926a.272.272 0 0 0 .14.047c.134 0 .24-.111.24-.247 0-.06-.023-.12-.038-.177l-.327-1.233a.582.582 0 0 1-.023-.156.49.49 0 0 1 .201-.398C23.024 18.48 24 16.82 24 14.98c0-3.21-2.931-5.837-6.656-6.088V8.89c-.135-.01-.27-.027-.407-.03zm-2.53 3.274c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983.976.976 0 0 1-.969-.983c0-.542.434-.982.969-.982zm4.844 0c.535 0 .969.44.969.982a.976.976 0 0 1-.969.983.976.976 0 0 1-.969-.983c0-.542.434-.982.969-.982z"/>
          </svg>
          <span id="wechatText">公众号: RoboticsCV</span>
        </span>
      </div>
    </div>
  </footer>
  
  <script>
    var webSocketCarInputUrl = "ws:\/\/" + window.location.hostname + "/cmd"; 
    let websocketCarInput;

    function initRobotInputWebSocket() {
      websocketCarInput = new WebSocket(webSocketCarInputUrl);
      websocketCarInput.onopen = function(event) {
        console.log('WebSocket is open now.');
      };
      websocketCarInput.onclose = function(event) {
        console.log('WebSocket is closed now. Reconnecting...');
        setTimeout(initRobotInputWebSocket, 2000);
      };
      websocketCarInput.onmessage = function(event) {
        let data = JSON.parse(event.data).raw;
        console.log('Battery monitor: ${data}%');
      };
    }

    function sendCommand(commandMode) {
      let command = 0;
      command |= (1<<commandMode);
      if (websocketCarInput && websocketCarInput.readyState === WebSocket.OPEN) {
        websocketCarInput.send(JSON.stringify({movementMode: command}));
        console.log('Sent command: ' + command);
      } else {
        console.log('WebSocket is not open. Cannot send command.');
      }
    }

    function sendSpeed(speed) {
      if (websocketCarInput && websocketCarInput.readyState === WebSocket.OPEN) {
        websocketCarInput.send(JSON.stringify({speed: parseFloat(speed)}));
        console.log('Sent speed: ' + speed);
      } else {
        console.log('WebSocket is not open. Cannot send speed.');
      }
    }

    function initSpeedControl() {
      const speedButtons = document.querySelectorAll('.speed-btn');
      
      let currentSpeed = 0.5; // 默认中速
      
      // 档位按钮点击事件
      speedButtons.forEach(button => {
        button.addEventListener('click', function() {
          // 移除所有按钮的active状态
          speedButtons.forEach(btn => btn.classList.remove('active'));
          // 添加当前按钮的active状态
          this.classList.add('active');
          
          // 更新当前速度值
          currentSpeed = parseFloat(this.dataset.speed);
          
          // 发送速度命令
          sendSpeed(currentSpeed);
          
          console.log('速度已切换到: ' + this.textContent + ' (值: ' + currentSpeed + ')');
        });
      });
    }

    // 语言切换功能
    let currentLang = 'zh'; // 默认中文

    const langTexts = {
      pageTitle: { zh: '机器人控制', en: 'Robot Control' },
      langButton: { zh: 'English', en: '中文' },
      speedLabel: { zh: '运动速度控制', en: 'Movement Speed Control' },
      footerTitle: { zh: '开源项目 · NodeHexa 六足机器人', en: 'Open Source · NodeHexa Hexapod Robot' },
      bilibiliText: { zh: 'B站: 智造师_RoboticsCV', en: 'Bilibili: 智造师_RoboticsCV' },
      githubText: { zh: 'GitHub: ViolinLee', en: 'GitHub: ViolinLee' },
      wechatText: { zh: '公众号: RoboticsCV', en: 'WeChat: RoboticsCV' },
      settingsBtn: { zh: '⚙️ 设置', en: '⚙️ Settings' },
      modalTitle: { zh: 'WiFi AP 配置', en: 'WiFi AP Settings' },
      labelSSID: { zh: 'AP 名称 (SSID)', en: 'AP Name (SSID)' },
      labelPassword: { zh: '密码 (8-63字符，留空为开放网络)', en: 'Password (8-63 chars, empty for open network)' },
      btnSave: { zh: '保存', en: 'Save' },
      btnCancel: { zh: '取消', en: 'Cancel' },
      btnReset: { zh: '恢复默认配置', en: 'Reset to Default' },
      currentConfig: { zh: '当前配置：', en: 'Current Config: ' },
      pendingMsg: { zh: '设备将在3秒后重启，请连接到新的AP：', en: 'Device will reboot in 3 seconds, please connect to new AP:' },
      pendingHint: { zh: '连接后访问 http://192.168.4.1 完成确认', en: 'Visit http://192.168.4.1 after connecting to confirm' }
    };

    function toggleLanguage() {
      currentLang = currentLang === 'zh' ? 'en' : 'zh';
      
      // 更新页面标题
      document.getElementById('pageTitle').textContent = langTexts.pageTitle[currentLang];
      
      // 更新语言切换按钮文本
      document.querySelector('.lang-switch').textContent = langTexts.langButton[currentLang];
      
      // 更新速度控制区域文本
      document.querySelector('.speed-label').textContent = langTexts.speedLabel[currentLang];
      
      // 更新速度档位按钮文本
      const speedButtons = document.querySelectorAll('.speed-btn[data-zh][data-en]');
      speedButtons.forEach(button => {
        button.textContent = button.getAttribute('data-' + currentLang);
      });
      
      // 更新所有按钮文本
      const buttons = document.querySelectorAll('.button[data-zh][data-en]');
      buttons.forEach(button => {
        button.textContent = button.getAttribute('data-' + currentLang);
      });
      
      // 更新设置按钮文本
      const settingsBtn = document.querySelector('.settings-btn');
      if (settingsBtn) {
        settingsBtn.textContent = langTexts.settingsBtn[currentLang];
      }
      
      // 更新页脚文本
      document.getElementById('footerTitle').textContent = langTexts.footerTitle[currentLang];
      document.getElementById('bilibiliText').textContent = langTexts.bilibiliText[currentLang];
      document.getElementById('githubText').textContent = langTexts.githubText[currentLang];
      document.getElementById('wechatText').textContent = langTexts.wechatText[currentLang];
      
      // 更新模态框文本
      updateModalTexts();
      
      console.log('Language switched to: ' + (currentLang === 'zh' ? '中文' : 'English'));
    }

    function updateModalTexts() {
      document.getElementById('modalTitle').textContent = langTexts.modalTitle[currentLang];
      document.getElementById('labelSSID').textContent = langTexts.labelSSID[currentLang];
      document.getElementById('labelPassword').textContent = langTexts.labelPassword[currentLang];
      document.getElementById('btnSave').textContent = langTexts.btnSave[currentLang];
      document.getElementById('btnCancel').textContent = langTexts.btnCancel[currentLang];
      document.getElementById('btnReset').textContent = langTexts.btnReset[currentLang];
      const currentInfo = document.getElementById('currentInfo');
      if (currentInfo) {
        currentInfo.innerHTML = '<strong>' + langTexts.currentConfig[currentLang] + '</strong><br><span id="currentSSID">加载中...</span>';
      }
    }

    // AP 配置功能
    function openSettings() {
      document.getElementById('settingsModal').style.display = 'block';
      loadAPConfig();
    }

    function closeSettings() {
      document.getElementById('settingsModal').style.display = 'none';
      document.getElementById('settingsForm').style.display = 'block';
      document.getElementById('pendingInfo').style.display = 'none';
      document.getElementById('statusMessage').style.display = 'none';
    }

    function loadAPConfig() {
      fetch('/api/ap-config?includePassword=true')
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success') {
            if (data.pending) {
              // 显示待确认信息
              document.getElementById('settingsForm').style.display = 'none';
              document.getElementById('pendingInfo').style.display = 'block';
              document.getElementById('newSSID').textContent = data.nextSSID || data.ssid;
              if (data.nextPassword) {
                document.getElementById('newPassword').textContent = '密码: ' + data.nextPassword;
                document.getElementById('wifiQRText').textContent = 'WIFI:T:WPA;S:' + data.nextSSID + ';P:' + data.nextPassword + ';;';
              } else {
                document.getElementById('newPassword').textContent = '开放网络（无密码）';
                document.getElementById('wifiQRText').textContent = 'WIFI:T:nopass;S:' + data.nextSSID + ';;';
              }
              document.getElementById('pendingMessage').textContent = langTexts.pendingMsg[currentLang];
              document.querySelector('#pendingInfo p[style]').textContent = langTexts.pendingHint[currentLang];
            } else {
              // 显示当前配置
              document.getElementById('apSSID').value = data.ssid || '';
              document.getElementById('apPassword').value = data.password || '';
              document.getElementById('currentSSID').textContent = data.ssid + (data.password ? ' (已设置密码)' : ' (开放网络)');
            }
          }
        })
        .catch(error => {
          console.error('加载配置失败:', error);
          showStatus('加载配置失败: ' + error.message, 'error');
        });
    }

    function saveAPConfig() {
      const ssid = document.getElementById('apSSID').value.trim();
      const password = document.getElementById('apPassword').value;

      if (!ssid) {
        showStatus('请输入AP名称', 'error');
        return;
      }

      if (ssid.length > 31) {
        showStatus('AP名称不能超过31个字符', 'error');
        return;
      }

      if (password && password.length > 0 && password.length < 8) {
        showStatus('密码至少需要8个字符', 'error');
        return;
      }

      const config = {
        ssid: ssid,
        password: password
      };

      fetch('/api/ap-config', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(config)
      })
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success') {
            // 显示待确认信息
            document.getElementById('settingsForm').style.display = 'none';
            document.getElementById('pendingInfo').style.display = 'block';
            document.getElementById('newSSID').textContent = data.nextSSID;
            if (data.nextPassword) {
              document.getElementById('newPassword').textContent = '密码: ' + data.nextPassword;
              document.getElementById('wifiQRText').textContent = 'WIFI:T:WPA;S:' + data.nextSSID + ';P:' + data.nextPassword + ';;';
            } else {
              document.getElementById('newPassword').textContent = '开放网络（无密码）';
              document.getElementById('wifiQRText').textContent = 'WIFI:T:nopass;S:' + data.nextSSID + ';;';
            }
            document.getElementById('pendingMessage').textContent = langTexts.pendingMsg[currentLang];
            document.querySelector('#pendingInfo p[style]').textContent = langTexts.pendingHint[currentLang];
          } else {
            showStatus('保存失败: ' + (data.message || '未知错误'), 'error');
          }
        })
        .catch(error => {
          console.error('保存配置失败:', error);
          showStatus('保存配置失败: ' + error.message, 'error');
        });
    }

    function resetAPConfig() {
      if (!confirm(currentLang === 'zh' ? '确定要恢复默认配置吗？设备将重启。' : 'Reset to default? Device will reboot.')) {
        return;
      }

      // 为避免设备重启导致请求挂起，增加超时控制；超时或网络错误均视为已下发重启指令
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 3500);

      // 使用 GET 提交复位请求，后端同时支持 GET/POST
      fetch('/api/ap-config/reset', { signal: controller.signal })
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success') {
            showStatus(currentLang === 'zh' ? '已恢复默认配置，设备将重启' : 'Reset to default, device will reboot', 'success');
            setTimeout(() => {
              closeSettings();
            }, 2000);
          } else {
            showStatus('重置失败: ' + (data.message || '未知错误'), 'error');
          }
        })
        .catch(error => {
          // 将网络失败/超时视为设备正在重启，给出正向提示，避免“Failed to fetch”误导
          showStatus(currentLang === 'zh' ? '已恢复默认配置，设备将重启' : 'Reset to default, device will reboot', 'success');
          setTimeout(() => {
            closeSettings();
          }, 2000);
        })
        .finally(() => {
          clearTimeout(timeoutId);
        });
    }

    function showStatus(message, type) {
      const statusEl = document.getElementById('statusMessage');
      statusEl.textContent = message;
      statusEl.className = 'status-message status-' + type;
      statusEl.style.display = 'block';
      setTimeout(() => {
        statusEl.style.display = 'none';
      }, 5000);
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
      const modal = document.getElementById('settingsModal');
      if (event.target === modal) {
        closeSettings();
      }
    }

    window.onload = function() {
      initRobotInputWebSocket();
      initSpeedControl();
      // 默认显示中文，无需调用toggleLanguage
      updateModalTexts();
      
      // 检查是否有待确认的配置
      fetch('/api/ap-config')
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success' && data.pending) {
            // 自动确认 pending 配置（用户已在新 AP 下访问页面）
            fetch('/api/ap-config/confirm', { method: 'POST' })
              .then(() => console.log('AP配置已确认'));
          }
        })
        .catch(error => console.error('检查配置状态失败:', error));
    };
  </script>
</body>
</html>